package com.itheima.project.mainPage;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.viewpager.widget.ViewPager;

import com.google.gson.Gson;
import com.itheima.project.HandlerUtil;
import com.itheima.project.OkHttpUtil;
import com.itheima.project.R;
import com.itheima.project.constant.ApiInterface;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class FragmentMainPage extends Fragment {

    // RecyclerView 列表
    private RecyclerView rvContent;
    //广告列表 轮播 进程
    private MyHandler myHandler;
    //下拉 刷新 控件
    private SwipeRefreshLayout srlArticel;
    // 数据 集合
    private List<RecyclerViewEntity.DataBean.DatasBean> mRecyclerViewList = new ArrayList<>();

    private int mCurrentPage = 0;
    // RecyclerView Adapter
    private RecyclerViewAdapter recycleradapter;
    //广告 ViewPage
    private ViewPager vpBanner;
    //广告 页面 视图
    private View inflate;
    //广告 页面 title 内容 显示
    private TextView tvTitle;
    //广告 页数 显示
    private TextView tvIndicator;
    // 用来获取当前数据数量，用于轮播图
    private static int size;



    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.main_page_fragment, null, false);
        rvContent = inflate.findViewById(R.id.rv_content_main_page_fragment);
        srlArticel = inflate.findViewById(R.id.srl_articel_main_page);
        return inflate;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initData();
        requestViewPage();
        requestRecyclerView();
        initEvent();
    }

    private void initData() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        rvContent.setLayoutManager(linearLayoutManager);

        inflate = LayoutInflater.from(getContext()).inflate(R.layout.viewpage_adapter, rvContent, false);
        vpBanner = inflate.findViewById(R.id.vp_banner_item_banner_adapter);
        tvTitle = inflate.findViewById(R.id.tv_title_item_banner_adapter);
        tvIndicator = inflate.findViewById(R.id.tv_indicator_item_banner_adapter);


        recycleradapter = new RecyclerViewAdapter(getContext(), mRecyclerViewList,inflate);
        rvContent.setAdapter(recycleradapter);
        requestRecyclerView();

    }

    private void requestViewPage() {
        OkHttpUtil.enqueue(ApiInterface.VIEWPAGE_URL, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                final ViewPageEntity viewPageEntity = new Gson().fromJson(string, ViewPageEntity.class);
                size = viewPageEntity.getData().size();
                if (viewPageEntity.getErrorCode() == 0) {
                    HandlerUtil.post(new Runnable() {
                        private MyHandler myHandler;

                        @Override
                        public void run() {
                            final List<ViewPageEntity.DataBean> data = viewPageEntity.getData();

                            ViewPageAdapter adapter = new ViewPageAdapter(getContext(), data);
                            vpBanner.setAdapter(adapter);
                            tvTitle.setText(data.get(0).getTitle());

                            vpBanner.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                                @Override
                                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                                }

                                @Override
                                public void onPageSelected(int position) {
                                    tvTitle.setText(data.get(position).getTitle());
                                    tvIndicator.setText(position + 1 + "/" + data.size());
                                }

                                @Override
                                public void onPageScrollStateChanged(int state) {

                                }
                            });

                            //设置滑动 图片
                            //    vpBanner.setCurrentItem(500000000);
                            myHandler = new MyHandler(FragmentMainPage.this);
                            myHandler.sendEmptyMessageDelayed(MyHandler.MOVE_TO_NEXT, 3000);
                            vpBanner.setOnTouchListener(new View.OnTouchListener() {
                                @Override
                                public boolean onTouch(View v, MotionEvent event) {
                                    switch (event.getAction()) {
                                        //手指按下
                                        case MotionEvent.ACTION_DOWN:
                                            myHandler.removeCallbacksAndMessages(null);
                                            break;
                                        //手指抬起
                                        case MotionEvent.ACTION_UP:
                                            myHandler.sendEmptyMessageDelayed(
                                                    MyHandler.MOVE_TO_NEXT,
                                                    3000);
                                            break;
                                    }
                                    return false;
                                }
                            });
                        }
                    });
                }


            }
        });

    }

    private void requestRecyclerView() {
        String url = String.format(ApiInterface.RECYCLERVIEW_URL, mCurrentPage);
        OkHttpUtil.enqueue(url, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                final RecyclerViewEntity recyclerViewEntity = new Gson().fromJson(string, RecyclerViewEntity.class);
                if (recyclerViewEntity.getErrorCode() == 0) {
                    HandlerUtil.post(new Runnable() {
                        @Override
                        public void run() {
                            if (mCurrentPage == 0) {
                                mRecyclerViewList.clear();
                            }
                            mRecyclerViewList.addAll(recyclerViewEntity.getData().getDatas());
                            recycleradapter.notifyDataSetChanged();
                            srlArticel.setRefreshing(false);

                        }
                    });
                }
            }
        });
    }

    private void initEvent() {
        srlArticel.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            //下拉刷新回调方法
            @Override
            public void onRefresh() {
                mCurrentPage = 0;
                requestRecyclerView();
            }
        });
        rvContent.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                LinearLayoutManager layoutManager = (LinearLayoutManager) rvContent.getLayoutManager();
                int itemCount = layoutManager.getItemCount();
                //一条都没有，就不要加载更多了
                if (itemCount == 0) {
                    return;
                }
                //找到最后一条条目显示的位置
                int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
                //最后一条显示的位置等于条目数量减1，说明当前显示的就是最后一条
                if (lastVisibleItemPosition == itemCount - 1 &&
                        //newState == RecyclerView.SCROLL_STATE_IDLE说明RecyclerView结束滑动
                        newState == RecyclerView.SCROLL_STATE_IDLE) {
                    mCurrentPage += 1;
                    srlArticel.setRefreshing(true);
                    requestRecyclerView();
                }

            }
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if(mScrollCallback != null){
                    mScrollCallback.onScrolled(recyclerView, dx, dy);
                }
            }
        });
        rvContent.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()){
                    case MotionEvent.ACTION_UP:
                        if (mScrollCallback != null) {
                            mScrollCallback.onLeaveScreen();
                        }
                        break;
                }
                return false;
            }
        });
    }


    private static class MyHandler extends Handler {


        private static final int MOVE_TO_NEXT = 10000;
        private WeakReference<FragmentMainPage> mReference;

        private MyHandler(FragmentMainPage activity) {
            mReference = new WeakReference<FragmentMainPage>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                //定义常量10000，表示播放下一张轮播图的任务
                case MOVE_TO_NEXT:
                    FragmentMainPage activity = mReference.get();
                    if (activity != null) {
                        int currentItem = activity.vpBanner.getCurrentItem();
                        activity.vpBanner.setCurrentItem(currentItem + 1);
                        //如果图片位于最后一张 就跳转到第一张重新轮播
                        if (currentItem == size-1) {
                            activity.vpBanner.setCurrentItem(0);
                        }
                        sendEmptyMessageDelayed(MOVE_TO_NEXT, 3000);
                        /*
                        此处有bug。当用手指滑动ViewPager的时候，
                        显示的当前条目，index值不对
                        解决方案：
                        1.当手指按下ViewPager的时候，撤回任务 removeMessages();
                        2.当手指离开ViewPager的时候，添加任务 sendMessageDelayed();
                         */
                        /*Message obtain = Message.obtain();
                        obtain.what = MOVE_TO_NEXT;
                        obtain.obj = itemIndex + 1;
                        sendMessageDelayed(obtain, 3_000);*/
                    }
                    break;
                default:
                    break;
            }
        }
    }
    public void scrollToTop(){
        rvContent.scrollToPosition(0);
    }

    private ScrollCallBack mScrollCallback;

    public void setScrollCallBack (ScrollCallBack scrollCalBack){
        this.mScrollCallback = scrollCalBack;
    }

    public interface ScrollCallBack{
        void onScrolled(RecyclerView recyclerView, int dx, int dy);

        void onLeaveScreen();
    }
}
